package com.guo.dms.common.menu.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.guo.dms.common.menu.entity.Menu;
import com.guo.dms.common.menu.service.MenuService;
import com.guo.dms.dept.permission.service.PermissionService;

@Controller
@RequestMapping("/sys/menu")
public class MenuController {
	@Autowired
	private MenuService menuService;
	
	@Autowired
	private PermissionService permissionService;
	
	@RequestMapping("")
	public String list(ModelMap model){
		model.addAttribute("menuTree",menuService.getMenuTree()); 
	  return "common/menu/list";
	}
	
	
	@RequestMapping("add/{parentId}")
	public String add(@PathVariable Integer parentId,ModelMap model){
		model.addAttribute("parentMenu",menuService.getMenuById(parentId));
		model.addAttribute("allPermissions", permissionService.getAllPermissions());
		return "common/menu/form";
	}
	/**
	 * 修改当前menu
	 * @return
	 */
	@RequestMapping(value="edit/{id}",method=RequestMethod.GET)
	public String editMenuForm(@PathVariable Integer id,ModelMap model){
		Menu currentMenu = menuService.getMenuById(id);
		//加载menu和其父节点
		model.addAttribute("currentMenu", currentMenu);
		model.addAttribute("allPermissions", permissionService.getAllPermissions());
		model.addAttribute("parentMenu",menuService.getMenuById(currentMenu.getParentId()));
		return "common/menu/form";
	}
	/**
	 * 添加和修改 menu
	 * @return
	 */
	@RequestMapping(value="save",method=RequestMethod.POST)
	public String editMenu(Menu menu){
		System.out.println(menu);
		boolean issuc = false;
		 if(menu.getId()==null || menu.getId()==0 ){
			issuc=menuService.addMenu(menu);
		}else{
			issuc=menuService.alertMenu(menu);
		} 
		 if(issuc){
			 System.out.println("menu :"+menu.getName()+" save success   !!");
		 }else{
			 System.err.println("menu :"+menu.getName()+" save faild   !!");
		 }
		return "redirect:/sys/menu";
	}
	
	
}
